package com.kavadani.profiles;

import java.util.ArrayList;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.kavadani.app.PatrolCarApp;
import com.kavadani.dialogs.ErrorDlg;
import com.kavadani.dialogs.ProgressDlg;

public class LoginActivity extends RemoteServiceClientActivity {

	private static String _MAP_PACKAGE_NAME = "com.kavadani.googlemap";
	private static String _MAP_ACTIVITY_NAME = "com.kavadani.googlemap.Navigation";

	// --- App --
	protected PatrolCarApp app; 
	
	// --- --------------------------------------
	boolean bLogin = false;
	
	private ImageView imageView1;
	private TextView textProfile;
	
	private ListView listView1;
	
	private TextView textMessage;
	private TextView textStatus;
	
	private static ProfileItem[] _PROFILES = {};
	
	private static class EfficientAdapter extends BaseAdapter {
		private LayoutInflater mInflater;
	    private Bitmap mIcon1, mIcon2;

	    public EfficientAdapter(Context context) {
	            // Cache the LayoutInflate to avoid asking for a new one each time.
	            mInflater = LayoutInflater.from(context);

	            // Icons bound to the rows.
	            mIcon1 = BitmapFactory.decodeResource(context.getResources(), R.drawable.patrol_a);
	            mIcon2 = BitmapFactory.decodeResource(context.getResources(), R.drawable.patrol_b);
	    }

	    public int getCount() { return PatrolCarApp.PROFILES.length; }

	        public Object getItem(int position) {
	            return position;
	        }

	        public long getItemId(int position) {
	            return position;
	        }

	        public View getView(int position, View convertView, ViewGroup parent) {
	            // A ViewHolder keeps references to children views to avoid unneccessary calls
	            // to findViewById() on each row.
	            ViewHolder holder;

	            // When convertView is not null, we can reuse it directly, there is no need
	            // to reinflate it. We only inflate a new View when the convertView supplied
	            // by ListView is null.
	            if (convertView == null) {
	                convertView = mInflater.inflate(R.layout.list_item_icon_text, null);

	                // Creates a ViewHolder and store references to the two children views
	                // we want to bind data to.
	                holder = new ViewHolder();
	                holder.icon = (ImageView) convertView.findViewById(R.id.icon);
	                holder.label = (TextView) convertView.findViewById(R.id.label);
	                holder.text = (TextView) convertView.findViewById(R.id.text);
	               
	                convertView.setTag(holder);
	            } 
	            else {
	                // Get the ViewHolder back to get fast access to the TextView
	                // and the ImageView.
	                holder = (ViewHolder) convertView.getTag();
	            }

	            // Bind the data efficiently with the holder.
	            holder.label.setText(PatrolCarApp.PROFILES[position].getLabel());
	            holder.text.setText(PatrolCarApp.PROFILES[position].getText());
	          
	            holder.icon.setImageBitmap((position % 2) == 0 ? mIcon1 : mIcon2);

	            return convertView;
	        }

	        static class ViewHolder {
	            TextView label;
				TextView text;
	            ImageView icon;
	        }
	    }
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		setContentView(R.layout.login_activity);
		
		this.app = (PatrolCarApp) this.getApplication();
		
		// --
		imageView1 = (ImageView)findViewById(R.id.imageView1);
		textProfile = (TextView)findViewById(R.id.textProfile);
		textMessage = (TextView)findViewById(R.id.textMessage);
		textStatus = (TextView)findViewById(R.id.textStatus);
		// --
		listView1 = (ListView) findViewById(R.id.listView1);
		
		listView1.setAdapter(new EfficientAdapter(this));
		
		listView1.setTextFilterEnabled(true);
		listView1.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
		listView1.setOnItemClickListener(new OnItemClickListener(){
			@Override
			public void onItemClick(AdapterView<?> arg0, View view, int position, long id) {
				listView1.setItemChecked(position, true);
				
				//openMapView();
								
				EnterPassword.show(LoginActivity.this,PatrolCarApp.PROFILES[position],
						new DialogInterface.OnClickListener() {
							@Override
							public void onClick(DialogInterface dialog, int which) {
								// closeLoginView();
								requestProfile();
							}
						});
				
			}});
		// --
		
/*		buttonLogin = (Button)findViewById(R.id.buttonLogin);
		buttonLogin.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				
			}
		});
		
		
		// --
		button1 = (Button)findViewById(R.id.button1);
		button1.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				requestProfile();
				
			}
		});
*/
	}
	
	// --- ---------------------------	
	private void requestProfile() {
		JSONObject json = new JSONObject();
		try {
			json.put("action", "Profile");
			json.put("username", PatrolCarApp.username);
			json.put("password", PatrolCarApp.password);
		} 
		catch (JSONException e) { }
		//
		this.serviceSend(json);
	}
	
	// -- 
	
	private void requestSubjects() {
		JSONObject json = new JSONObject();
		try {
			json.put("action", "Subjects");
			
		}
		catch (JSONException e) { }
		// --
		this.serviceSend(json);
	}
	
	// --- ---------------------------
	
	private Bundle jsonToBundle(JSONObject json){
		JSONArray keys = json.names();
		
		for (int i = 0; i < keys.length(); i++) {
			String key = (String) keys.opt(i);
		}
		Bundle bundle = new Bundle();
		//bundle.put("profile-items", keys);
//		bundle.putStringArrayList("profile-items", map);
		return new Bundle();
	}
	
	private void openMapView() {
		Bundle bundle = new Bundle();
		
		callActivity(LoginActivity._MAP_ACTIVITY_NAME, LoginActivity._MAP_PACKAGE_NAME, bundle);
		//this.finish();
	}
	
	
	
	
	// -----------------------------------------------------------------------
	
	protected void onRequestFailed(Bundle bundle) {
		
		Log.e("RequestFailed", toJSON(bundle).toString());
	}
	
	protected void onReceive(JSONArray jarr) {
		Log.e("Receive ARR", jarr.toString());
	}
	
	protected void onReceive(JSONObject json) {
		Log.e("Receive OBJ", json.toString());
		ProgressDlg.close();

		String message = null;
		String action = null;
		try {
			message = json.getString("message");
			action = "Action: " + json.getString("action");
		} catch (JSONException e1) {
			action = e1.getMessage();
		}

		if (message != null) {
			ErrorDlg.show(this, action, message);
		}
	}
	
	protected void onRequestResult(JSONArray jarr) {
		Log.e("RequestResult ARR", jarr.toString());
	}
	
	
	
	protected void onRequestResult(JSONObject json) {
		
		Log.e("RequestResult OBJ", json.toString());
		
		String action = null;
		try {
			action = json.getString("action");
		}
		catch (JSONException e1) {
			// e1.printStackTrace();
			ProgressDlg.close();
			return;
		}
		
		if("Profile".equalsIgnoreCase(action)) {
			Intent intent = new Intent(this, ProfileActivity.class);
			try {
				intent.putExtra("image", json.getString("image"));
				intent.putExtra("username", json.getString("username"));
				intent.putExtra("full-name", json.getString("full-name"));
				intent.putExtra("company", json.getString("company"));
				intent.putExtra("image-type", json.getString("image-type"));
			} catch (JSONException e) {
				e.printStackTrace();
			}
			startActivity(intent);
			//callActivity(ProfileActivity._PROFILE_ACTIVITY_NAME, ProfileActivity._PROFILE_ACTIVITY_PACKAGE_NAME, bundle);
			this.finish();
			ProgressDlg.close();
			return;
		}
		
		if("Subjects".equalsIgnoreCase(action)) {
			
			ProgressDlg.close();
			
			JSONArray jarr;
			try {
				jarr = json.getJSONArray("list");
			}
			catch (JSONException e) {
				// e.printStackTrace();		
				// textView1.setText("Error: Request driver's list: failed.");
				return;
			}
			// textView1.setText(jarr.toString());
			
			if( !bLogin ) { 
				// --
				bLogin = true;
				ArrayList<ProfileItem> list = new ArrayList<ProfileItem>();
				// --
				int size = jarr.length();				
				for(int i = 0; i < size; i++) {
					json = jarr.optJSONObject(i);
					if(json == null) { continue; }
					// --
					list.add(new ProfileItem(json));
				}
				// --
				_PROFILES = list.toArray(new ProfileItem[list.size()]);
				
				if (_PROFILES.length!=PatrolCarApp.PROFILES.length) {
					PatrolCarApp.PROFILES = _PROFILES;
					this.finish();
					startActivity(getIntent());
				}
				
			} // --
		}
		
		
	}
	
	
	
	protected void onRemoteConnectionStatus() {
		if(this.remoteConnectionStatus < 2) { // not connected
			// ProgressDlg.show(this);
			ProgressDlg.setText("Connecting ...");
		}
		else if(this.remoteConnectionStatus == 2) { // waiting for activation
			// ProgressDlg.show(this);
			ProgressDlg.setText("Waiting for activation ...");
		}
		else {	// connected
			
			if( !bLogin ) {

				ProgressDlg.show(this);
				ProgressDlg.setText("Connected, request profiles ...");
				
				requestSubjects();
			}
			else {
				ProgressDlg.close();
			}
		}
	}
	
	
	// 
	protected void onServiceConnectionStatus(boolean connected) {
		this.setTitle(getString(R.string.app_name) + " - " 
				+ getString( connected ? R.string.status_connected : R.string.status_not_connected));
	}
	
	
}
